import { ComponentClass } from 'react'
import Taro, { Component } from '@tarojs/taro'
import { View, Text, Input, Form, Picker } from '@tarojs/components'
import { connect } from '@tarojs/redux'

import ApplyFormItem from '../../model/apply-form'
import { default as ProductUtils } from '../../utils/product'
import { User as UserUtils } from '../../utils/user'
import { Utils } from '../../utils/utils'
import { allJobsOptions } from '../../config'
import RegionPicker from '../region-picker'
import Constants from '../../config/constants'

import './index.scss'

const productUtils = new ProductUtils()
const userUtils = new UserUtils()
const utils = new Utils()

type FormItem = {
  name: string,
  value: any,
}

type PageStateProps = {}

type PageDispatchProps = {
  updateFormItem: (type: string, payload: {
    formItem: FormItem
  }) => void
}

type PageOwnProps = {
  form: Array<ApplyFormItem>,   // 表单项数组
  formValue: any,         // 表单值对象，用于更新表单
  dispatchType: string,   // 要出发action名称的字符串
  // regionRange: 1 | 2 | 3,    // 省市区的选项， 枚举值 1: 省 2: 省市 3: 省市区
}

type PageState = {
  regionOptions: any      // 省市区选项
}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface ApplyForm {
  props: IProps;
  state: PageState;
}

/**
 * 首页立即申请组件
 */
@connect(({ }) => ({}), (dispatch) => ({
  updateFormItem(type: string, payload: { formItem: FormItem }) {
    dispatch({
      type,
      payload,
    })
  },
}))
class ApplyForm extends Component {

  constructor(props) {
    super(props);

    // console.log('regionOptions = ', this.state.regionOptions)
  }

  componentDidMount() {
    this.initRegionPickerChangeWatch()
  }

  componentWillUnmount() {
    this.removeRegionPickerChangeWatch()
  }

  componentWillReceiveProps(nextProps) { }

  componentDidShow() { }

  componentDidHide() { }

  render() {
    const { form, formValue } = this.props
    // console.log('formValue = ', formValue)

    const items = form.map((item, index) => {

      return (<View className="row" key={index}>
        <Text className={`label ${item.isRequire ? 'require' : ''}`}>{item.label}</Text>
        <View className="content-box">

          {
            item.type === 'input' ?
              (<View className="content">
                <View className="input-box">
                  <Text className={ `input-text${ process.env.TARO_ENV === 'weapp' ? ' input-text-weapp' : ''}` }>{ item.toThrousand ? productUtils.toThousand(formValue[item.name]) : formValue[item.name] }</Text>
                  <Input name={item.name} type={item.inputType ? item.inputType : 'text'} 
                    value={ formValue[item.name] } 
                    onInput={this.onInputInput.bind(this, item.name)}
                    onBlur={this.onInputBlur.bind(this, item.name)}
                    placeholder={item.placeholder} 
                    data-name={item.name}/>
                </View>
                {
                  item.suffix ?
                    (<View className="suffix">
                      <Text>{item.suffix}</Text>
                    </View>) : null
                }
              </View>) : null
          }
          {
            item.type === 'select' && item.mode !== 'region' ? 
              (<Picker 
                name={item.name} 
                mode={item.mode ? item.mode : 'selector'} 
                onChange={this.onPickerChange.bind(this, item.name)} 
                value={item.options && item.options.length > 0 ? 
                  utils.getOptionIndex(formValue[item.name], item.options, item.optionValueKey) : ''} 
                range={item.options} 
                rangeKey={ item.rangeKey } 
                data-name={item.name}>
                <View className="content">
                  <View>
                    <Text className="text">
                      { // 没选中任何值时显示 placeholder
                        utils.isEmpty(formValue[item.name]) ? (<Text className="place-holder">{item.placeholder}</Text>) : null
                      }
                      {
                        item.options ? (!utils.isEmpty(formValue[item.name]) ? (<Text>{utils.getOptionName(formValue[item.name], item.options)}</Text>) : null) : ''
                      }
                    </Text>
                  </View>
                  <View>
                    <Text className="iconfont icon-icon1"></Text>
                  </View>
                </View>
              </Picker>) : null
          }
          {
            item.type === 'select' && item.mode === 'region' ?
              (<RegionPicker regionRange={item.regionRange ? item.regionRange : 3} regionCode={formValue[item.name]} eventRandom={`_${item.name}`} />) : null
          }
        </View>
      </View>)
    })

    return (
      <View className='apply-form-container'>
        <Form className='apply-form'>
          {items}
        </Form>
      </View>
    )
  }

  /**
   * 输入监听方法
   * @param name 表单项的name
   * @param e 
   */
  onInputInput(name, e) {
    // console.log('onInputInput, e = ', e)
    let target = e.target

    let { value } = target

    const optionItem = this.props.form.filter(item => {
      return item.name === name
    })
    if (optionItem.length === 1) {
      const { numberRangeMax, numberRangeMaxTips } = optionItem[0]
      if (numberRangeMax && numberRangeMax > 0) {
        if (value > numberRangeMax) {
          value = numberRangeMax
          Taro.showToast({
            title: numberRangeMaxTips ? numberRangeMaxTips.replace('%s', numberRangeMax.toString()) : '不能大于' + numberRangeMax,
            icon: 'none',
          })
        }
      }
    }

    this.props.updateFormItem(this.props.dispatchType, {
      formItem: {
        name,
        value,
      }
    })

    // 返回value，可以刷新输入框的值，对小程序有效
    return value
  }

  /**
   * 失去焦点监听方法
   * @param name 
   * @param e 
   */
  onInputBlur(name, e) {
    // console.log('onInputBlur, e = ', e)
    let { value } = e.detail

    const optionItem = this.props.form.filter(item => {
      return item.name === name
    })
    if (optionItem.length === 1) {
      const { numberRangeMin, numberRangeMax, numberRangeMinTips, numberRangeMaxTips } = optionItem[0]
      
      if (numberRangeMin && numberRangeMin > 0) {
        if (value < numberRangeMin) {
          value = numberRangeMin
          Taro.showToast({
            title: numberRangeMinTips ? numberRangeMinTips.replace('%s', numberRangeMin.toString()) : '不能小于' + numberRangeMin,
            icon: 'none',
          })
        }
      }

      if (numberRangeMax && numberRangeMax > 0) {
        if (value > numberRangeMax) {
          value = numberRangeMax
          Taro.showToast({
            title: numberRangeMaxTips ? numberRangeMaxTips.replace('%s', numberRangeMax.toString()) : '不能大于' + numberRangeMax,
            icon: 'none',
          })
        }
      }

      this.props.updateFormItem(this.props.dispatchType, {
        formItem: {
          name,
          value,
        }
      })
    }
  }

  /**
   * 选择器改变监听方法
   * @param name 表单项的name
   * @param e 
   */
  onPickerChange(name, e) {
    // console.log('onChange, e = ', e)

    let target = e.target

    const { value } = e.detail
    // const { name } = e.target.dataset

    const applyFormItems = this.props.form
    let targetItem: ApplyFormItem | null = null
    for (const item of applyFormItems) {
      if (item.name === name) {
        targetItem = item
        break
      }
    }

    if (targetItem) {
      const { options } = targetItem
      if (options) {
        const optionVal = utils.getOptionValueByIndex(value, options)
        // console.log('optionVal = ', optionVal)
        this.props.updateFormItem(this.props.dispatchType, {
          formItem: {
            name,
            value: optionVal,
          }
        })
      }
    }
  }

  /**
   * 初始化区域选择picker的监听
   */
  initRegionPickerChangeWatch() {
    // 查找是否有区域选择框
    const regionPickers = this.props.form.filter((item, index) => {
      return item.mode === 'region'
    })

    if (regionPickers) {

      regionPickers.forEach(element => {
        const { name } = element
        Taro.eventCenter.on(`${Constants.REGION_PICKER_CHANGE_EVENT}_${name}`, (regionParam) => {
          // console.log('REGION_PICKER_CHANGE_EVENT regionParam = ', regionParam)

          const { selectRegionCode, selectRegionIndex, selectRegionName } = regionParam

          this.props.updateFormItem(this.props.dispatchType, {
            formItem: {
              name,
              value: selectRegionCode
            }
          })

          this.props.updateFormItem(this.props.dispatchType, {
            formItem: {
              name: 'city_index',
              value: selectRegionIndex
            }
          })

          this.props.updateFormItem(this.props.dispatchType, {
            formItem: {
              name: 'city_name',
              value: selectRegionName
            }
          })
        })
      })
    }
  }

  /**
   * 删除区域选择picker的监听
   */
  removeRegionPickerChangeWatch() {
    // 查找是否有区域选择框
    const regionPickers = this.props.form.filter((item, index) => {
      return item.mode === 'region'
    })

    if (regionPickers) {
      regionPickers.forEach(element => {
        const { name } = element
        Taro.eventCenter.off(`${Constants.REGION_PICKER_CHANGE_EVENT}_${name}`)
      })
    }
  }
}

export default ApplyForm as ComponentClass<PageOwnProps, PageState>
